package com.nosweattechnet.mapmyway;

import java.util.ArrayList;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.OverlayItem;
import com.nosweattechnet.datatypes.Place;


//Holds the array of Places which are currently being shown on the main map
public class DisplayPlaces {
	//Holds the places to be displayed
	private static ArrayList<Place> places=new ArrayList<Place>();
	
	//Factors used to convert latitude and longitude from decimal notation to form used by the Google Maps API
	public static final float OVERLAY_LATITUDE_SCALE=1000000;
	public static final float OVERLAY_LONGITUDE_SCALE=1000000;
	
	//Adds a place if it is not already in the array
	public static void addPlace(Place place){
		if(shouldAdd(place)){
			places.add(place);
		}
	}
	
	//Adds places form a list, if they are not already in the array
	public static void addPlaces(ArrayList<Place> newplaces){
		for(Place p:newplaces){
			if(shouldAdd(p)){
				places.add(p);
			}
		}
	}
	
	//Removes all of the places from the array
	public static void clear(){
		places.clear();
	}
	
	//Gets the size of the array
	public static int size(){
		return places.size();
	}
	
	//Checks if the given place is already in the array
	private static boolean shouldAdd(Place place){
		if(place==null){
			return false;
		}
		for(Place p:places){
			if(p.equals(place)){
				return false;
			}
		}
		return true; 
	}
	
	//Creates an Google Maps OverlayItem for a given Place
	private static OverlayItem getOverLayItem(Place p){
		GeoPoint point = new GeoPoint((int) (p.getLatitude()*OVERLAY_LATITUDE_SCALE),(int) (p.getLongitude()*OVERLAY_LONGITUDE_SCALE));
	    OverlayItem overlayitem = new OverlayItem(point, p.getName(),p.getDescription());
	    return overlayitem;
	}
	
	//Clears the itemizedoveraly then adds all of the places in the array to it
	public static void addToItemizedOverlay(MapItemizedOverlay itemizedoverlay) {
		itemizedoverlay.clearPlaces();
		for(Place p:places){
			itemizedoverlay.addOverlay(getOverLayItem(p), p);
		}
	}
}
